﻿using System;
using System.Windows;
using CCF20Model;
using IWshRuntimeLibrary;
using System.Reflection;
using WiseLinkWPF.Windows.Controls;
using System.IO;
using CCF20Model.ConfigurationFile;
using CCF20.Shared;
using System.Globalization;
using System.Threading;
using WiseLink.RDS.Resource;

namespace CCF20Module
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    /// 
    public partial class App : System.Windows.Application
    {
        private int exceptionCount = 0;
        public static string AllowedPermission = string.Empty;
        public static string CurrentUser = string.Empty;
        public static string CurrentUserMobile = string.Empty;
        public static bool IsMobileBranch = false;
        
        
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception.Message.Contains("Dispatcher processing has been suspended"))
            {
                return;
            }
            if (e.Exception.Message.Contains("里程，周期不可同时为空"))
            {
                Utility.ShowMessageBox(Message.Startup_Mileage_Period_Null);
                return;
            }
            exceptionCount ++;
            if (exceptionCount > 11)
            {
                App.Current.Shutdown();
            }
            LoggerHelper.LogCCF20(string.Format("[Exception:]{0} \t [Stack:] {1}",
                                           e.Exception.Message,
                                           e.Exception.StackTrace));
           

            Exception innerException = e.Exception.InnerException;
            while (innerException != null)
            {
                LoggerHelper.LogCCF20(string.Format("[Inner Exception:]{0} \t [Stack:] {1}",
                                                        innerException.Message,
                                                        innerException.StackTrace ?? ""));
                innerException = innerException.InnerException;
            }
            e.Handled = true;
            Utility.ShowMessageBox(Message.Startup_RDSException);
            
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            CultureInfo ci;
            if ((bool)ConfiguraitonHelper.MyConfiguration.isenglish)
            {
                ci = new CultureInfo("en");
                
            }
            else
            {
                ci = new CultureInfo("zh");
            }

            LoggerHelper.LogCCF20(string.Format("Culture {0}", ci.Name));
            WiseLink.RDS.Resource.ButtonString.Culture = ci;
            WiseLink.RDS.Resource.CustomerTableString.Culture = ci;
            WiseLink.RDS.Resource.WiseLinkRDSStatus.Culture = ci;
            WiseLink.RDS.Resource.Message.Culture = ci;
            
            Thread.CurrentThread.CurrentUICulture = ci;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
            
         
            foreach(System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.Contains(currentProcess.ProcessName) && p.Id != currentProcess.Id)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception ex)
                    {
                        LoggerHelper.LogCCF20(string.Format("Clean up previous process {1}-{2} exception:{0}",ex.Message, p.ProcessName,p.StartTime.ToLongTimeString()));
                    }
                    LoggerHelper.LogCCF20("Clean up previous process");
                }
            }
            


            LoggerHelper.LogCCF20("CCF20 Started");
            //LocalizationManager.Manager = new CustomLocalizationManager();
            if (e.Args.Length > 0)
            {
                if (e.Args[0] == "MobileBranch")
                {
                    IsMobileBranch = true;
                    LoggerHelper.LogCCF20("MobileBranch");
                    return;
                }
            }


            string strResult = CheckConfiguration();
            if (strResult.Length > 0)
            {
                LoggerHelper.LogCCF20(strResult);
                Utility.ShowMessageBox(Message.Startup_Configurtion_Change);
                App.Current.Shutdown();
            }

            //为ZicMonitor在PROGRAM MENU中创建ShortCut
            CCF20Helper.CreateShortCut(ZICMonitorModel.ConfigurationPath,
                                        "ZICMonitor",
                                        Assembly.GetExecutingAssembly().Location.Replace("车务通无忧驾驶系统", "ZicMonitor"),
                                        Assembly.GetExecutingAssembly().Location.Replace("车务通无忧驾驶系统.exe",string.Empty));
            
            //CCF20Helper.RemoveShortCut("移动营业厅");

        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            LoggerHelper.FlushLog();
        }

        public static string CheckConfiguration()
        {
            ConfigurationBase configuration = new ConfigurationBase();
            CCFConnection ccfConnection = new CCFConnection(configuration);
            MembershipConnection memberShipConnection = new MembershipConnection(ccfConnection);
            CCFLog ccfLog = new CCFLog(memberShipConnection);
            ZICMonitorConnection zicConnection = new ZICMonitorConnection(ccfLog);
            ZICMonitorLog zicLog = new ZICMonitorLog(zicConnection);
            OtherConfiguration otherConfig = new OtherConfiguration(zicLog);
            return otherConfig.VerifyResult().Trim();
            
        }
        
    }
    
    
}
